<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['blog:blogUser:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['blog:blogUser:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['blog:blogUser:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['blog:blogUser:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="blogUserList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户名" align="center" prop="userName" />
      
      <el-table-column label="手机号" align="center" prop="phoneNumber" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="角色" align="center" prop="roleName" >
        <template #default="scope">
          <el-tag v-for="item in scope.row.blogRole" style="margin-right: 5px;">
            {{item.roleName}}
          </el-tag> 
        </template>
      </el-table-column>
      <el-table-column label="账号状态" align="center" width="100">
            <template #default="scope">
               <el-switch
                  v-model="scope.row.status"
                  active-value="0"
                  inactive-value="1"
                  @change="handleStatusChange(scope.row)"
               ></el-switch>
            </template>
         </el-table-column>
    
      
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="info"  @click="handleInfo(scope.row)" v-hasPermi="['blog:blogUser:list']">详情</el-button>
          <el-button link type="info"  @click="handleUpdate(scope.row)" v-hasPermi="['blog:blogUser:edit']">修改</el-button>
          <el-button link type="info"  @click="handleDelete(scope.row)" v-hasPermi="['blog:blogUser:remove']">删除</el-button>
          <el-button link type="info"  @click="handleResetPwd(scope.row)" v-hasPermi="['blog:blogUser:edit']">重置密码</el-button>
          
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="blogUserRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
        <!-- 用户性别 字典选择框 -->
         <el-form-item label="性别" prop="sex">
          <!-- 选择框 -->
           <el-select v-model="form.sex"  style="width: 100px;">
            <el-option
              v-for="dict in sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
         </el-form-item>
         <!-- 用户角色 查询回显 -->
         <el-form-item label="角色">
              <el-select v-model="form.roleIds" multiple placeholder="请选择">
                <el-option 
                  v-for="item in blogRoleList" 
                  :key="item.id" 
                  :label="item.roleName" 
                  :value="item.id" 
                  :disabled="item.status == 1">
                </el-option>
              </el-select>
            </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <image-upload v-model="form.avatar"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog :title="title" v-model="infoOpen" width="500px" append-to-body>
      <el-descriptions  :column="1"  border label-width="100px" >
        <el-descriptions-item  label="昵称"  label-align="center">
          <span>{{ form.nickName }}</span>
        </el-descriptions-item>
        <el-descriptions-item  label="账户名称" label-align="center">
          <span>{{ form.userName }}</span>
        </el-descriptions-item>
        <el-descriptions-item  label="角色" label-align="center">
          <el-tag v-for="item in form.blogRole" style="margin-right: 5px;">{{item.roleName}}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item  label="性别" label-align="center">
          <span>{{ form.sex == "0" ? "男" : "女" }}</span>
        </el-descriptions-item>

        <el-descriptions-item  label="状态" label-align="center">
          {{ form.status == "0" ?"正常" : "禁用" }}
        </el-descriptions-item>
        <el-descriptions-item  label="邮箱" label-align="center">
          <span>{{ form.email }}</span>
        </el-descriptions-item>
        <el-descriptions-item  label="手机号" label-align="center">
          <span>{{ form.phoneNumber }}</span>
        </el-descriptions-item>
       
        <el-descriptions-item  label="创建时间" label-align="center">
          <span>{{ form.createTime }}</span>
        </el-descriptions-item>
        <el-descriptions-item  label="头像" label-align="center">
          <image-preview :src="form.avatar" :width="50" :height="50"/>
        </el-descriptions-item>
      </el-descriptions>
      
    </el-dialog>
  </div>
</template>

<script setup name="BlogUser">
import { listBlogUser, getBlogUser, delBlogUser, addBlogUser, updateBlogUser,resetUserPwd } from "@/api/blog/blogUser";
import {listBlogRole} from "@/api/blog/blogRole";
import { loadAllParams } from "@/api/params";

const { proxy } = getCurrentInstance();
const { sys_user_sex } = proxy.useDict("sys_user_sex");

const blogUserList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const infoOpen = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    nickName: null,
    roleIds: [],
    blogRole:[],
    status: null,
    email: null,
    phoneNumber: null,
    sex: null,
    createTime: null,
    updateTime: null,
  },
  rules: {
    nickName: [
      { required: true, message: '请输入用户昵称', trigger: 'blur' }
    ],
    email: [
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    phoneNumber: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: ['blur', 'change'] }
    ],
    sex: [
      { required: true, message: '请选择性别', trigger: 'blur' }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);
const blogRoleList = ref([]);

/** 查询用户管理列表 */
function getList() {
  loading.value = true;
  listBlogUser(queryParams.value).then(response => {
    blogUserList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userName: null,
    nickName: null,
    roleIds: [],
    blogRole:[],
    status: null,
    email: null,
    phoneNumber: null,
    sex: null,
    avatar: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null
  };
  proxy.resetForm("blogUserRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 账号状态修改 */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.userName + '"角色吗?').then(function () {
    let params = { id: row.id, status: row.status };
    return updateBlogUser(params);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0";
  });
}


/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户管理";

  listBlogRole(loadAllParams).then(response => {
      blogRoleList.value = response.rows;
      console.log(blogUserList.value)
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getBlogUser(_id).then(response => {
    form.value = response.data;
    form.value.roleIds = response.roleIds
    open.value = true;
    title.value = "修改用户管理";
  });

  listBlogRole(loadAllParams).then(response => {
      blogRoleList.value = response.rows;
      console.log(blogUserList.value)
  });
}

/** 查看详情按钮操作 */
function handleInfo(row) {
  reset();
  const _id = row.id 
  getBlogUser(_id).then(response => {
    form.value = response.data;
    infoOpen.value = true;
    title.value = "用户详情";
  });
}

/** 重置密码 */
function handleResetPwd(row) {
  proxy.$modal.confirm('是否确认重置"' + row.userName + '"的密码?').then(function() {
    return resetUserPwd(row.id);
  }).then(() => {
    proxy.$modal.msgSuccess("重置成功，新密码为" + "123456");
  }).catch(() => {});
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["blogUserRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBlogUser(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBlogUser(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除用户管理编号为"' + _ids + '"的数据项？').then(function() {
    return delBlogUser(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('blog/blogUser/export', {
    ...queryParams.value
  }, `blogUser_${new Date().getTime()}.xlsx`)
}

getList();
</script>
